package com.xiaoxu.content.service.impl;

import com.alibaba.fastjson.JSON;
import com.xiaoxu.base.exception.bkSchoolException;
import com.xiaoxu.content.config.MultipartSupportConfig;
import com.xiaoxu.content.dao.CourseBaseMapper;
import com.xiaoxu.content.dao.CourseMarketMapper;
import com.xiaoxu.content.dao.CoursePublishMapper;
import com.xiaoxu.content.feignclient.MediaServiceClient;
import com.xiaoxu.content.feignclient.SearchServiceClient;
import com.xiaoxu.content.model.dto.CourseBaseInfoDto;
import com.xiaoxu.content.model.dto.CoursePreviewDto;
import com.xiaoxu.content.model.dto.TeachplanDto;
import com.xiaoxu.content.model.po.*;
import com.xiaoxu.content.service.*;
import com.xiaoxu.content.service.jobHandler.CoursePublishTask;
import com.xiaoxu.messagesdk.model.po.MqMessage;
import com.xiaoxu.messagesdk.service.MqMessageService;
import com.xiaoxu.search.model.po.CourseIndex;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author xiaoxu
 * @version 1.0
 * @description TODO
 * @date 2023/1/29 19:46
 */
@Service
@Slf4j
public class CoursePublishServiceImpl implements CoursePublishService {

    private final CourseBaseService courseBaseService;
    private final TeachplanService teachplanService;
    private final CourseTeacherService courseTeacherService;
    private final CourseBaseMapper courseBaseMapper;
    private final CourseMarketMapper courseMarketMapper;
    private final CoursePublishPreService coursePublishPreService;
    private final CoursePublishMapper coursePublishMapper;
    private final MqMessageService mqMessageService;
    private final MediaServiceClient mediaServiceClient;
    private final SearchServiceClient searchServiceClient;

    public CoursePublishServiceImpl(CourseBaseService courseBaseService, TeachplanService teachplanService, CourseTeacherService courseTeacherService, CourseBaseMapper courseBaseMapper, CourseMarketMapper courseMarketMapper, CoursePublishPreService coursePublishPreService, CoursePublishMapper coursePublishMapper,MqMessageService mqMessageService,MediaServiceClient mediaServiceClient,SearchServiceClient searchServiceClient) {
        this.courseBaseService = courseBaseService;
        this.teachplanService = teachplanService;
        this.courseTeacherService = courseTeacherService;
        this.courseBaseMapper = courseBaseMapper;
        this.courseMarketMapper = courseMarketMapper;
        this.coursePublishPreService = coursePublishPreService;
        this.coursePublishMapper = coursePublishMapper;
        this.mqMessageService = mqMessageService;
        this.mediaServiceClient = mediaServiceClient;
        this.searchServiceClient = searchServiceClient;
    }

    /**
     * @param courseId 课程id
     * @return CoursePreviewDto
     * @description 获取课程预览信息
     */
    @Override
    public CoursePreviewDto getCoursePreviewInfo(Long courseId) {
        //课程基本信息、营销信息
        CourseBaseInfoDto courseBaseInfo = courseBaseService.queryCourseInfoById(courseId);
        //课程计划信息
        List<TeachplanDto> teachplanTree = teachplanService.findTeachplayTree(courseId);
        //师资信息
        List<CourseTeacher> teachers = courseTeacherService.findCourseTeacherList(courseId);
        //设置返回属性
        CoursePreviewDto coursePreviewDto = new CoursePreviewDto();
        coursePreviewDto.setCourseBase(courseBaseInfo);
        coursePreviewDto.setTeachplans(teachplanTree);
        coursePreviewDto.setTeachers(teachers);
        return coursePreviewDto;
    }

    /**
     * @description 提交审核
     * @param companyId 机构Id
     * @param courseId  课程id
     */
    @Override
    @Transactional
    public void commitAudit(Long companyId, Long courseId) {
        //约束校验
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        if (courseBase == null){
            throw new bkSchoolException("系统异常，找不到该课程");
        }
        //课程审核状态
        String auditStatus = courseBase.getAuditStatus();
        //当前审核状态为已提交不允许再次提交
        if("202003".equals(auditStatus)){
            throw new bkSchoolException("当前为等待审核状态，审核完成可以再次提交。");
        }
        //本机构只允许提交本机构的课程
        if(!courseBase.getCompanyId().equals(companyId)){
            throw new bkSchoolException("不允许提交其它机构的课程。");
        }
        //课程图片是否填写
        if(StringUtils.isEmpty(courseBase.getPic())){
            throw new bkSchoolException("提交失败，请上传课程图片");
        }
        //添加课程预发布记录
        CoursePublishPre coursePublishPre = new CoursePublishPre();
        //课程基本信息加部分营销信息
        CourseBaseInfoDto courseBaseInfo = courseBaseService.queryCourseInfoById(courseId);
        BeanUtils.copyProperties(courseBaseInfo,coursePublishPre);
        //课程营销信息
        CourseMarket courseMarket = courseMarketMapper.selectById(courseId);
        //转为json
        String courseMarketJson = JSON.toJSONString(courseMarket);
        //将课程营销信息json数据放入课程预发布表
        coursePublishPre.setMarket(courseMarketJson);
        //查询课程计划信息
        List<TeachplanDto> teachplanTree = teachplanService.findTeachplayTree(courseId);
        if(teachplanTree.size()<=0){
            throw new bkSchoolException("提交失败，还没有添加课程计划");
        }
        //转json
        String teachplanTreeString = JSON.toJSONString(teachplanTree);
        coursePublishPre.setTeachplan(teachplanTreeString);
        //设置预发布记录状态,已提交
        coursePublishPre.setStatus("202003");
        //教学机构id
        coursePublishPre.setCompanyId(companyId);
        //提交时间
        coursePublishPre.setCreateDate(LocalDateTime.now());
        boolean b = coursePublishPreService.saveOrUpdate(coursePublishPre);
        if(!b){
            throw new bkSchoolException("错误，系统异常，请联系管理员");
        }
        //更新课程基本表的审核状态
        courseBase.setAuditStatus("202003");
        courseBaseMapper.updateById(courseBase);
    }

    @Transactional
    @Override
    public void publish(Long companyId, Long courseId) {
        //约束校验
        //查询课程预发布表
        CoursePublishPre coursePublishPre = coursePublishPreService.getById(courseId);
        if(coursePublishPre == null){
            throw new bkSchoolException("请先提交课程审核，审核通过才可以发布");
        }
        //本机构只允许提交本机构的课程
        if(!coursePublishPre.getCompanyId().equals(companyId)){
            throw new bkSchoolException("不允许提交其它机构的课程。");
        }
        //课程审核状态
        String auditStatus = coursePublishPre.getStatus();
        //审核通过方可发布
        if(!"202004".equals(auditStatus)){
            throw new bkSchoolException("操作失败，课程审核通过方可发布。");
        }
        //保存课程发布信息
        saveCoursePublish(courseId);
        //保存消息表
        saveCoursePublishMessage(courseId);
        //删除课程预发布表对应记录
        coursePublishPreService.removeById(courseId);
    }

    /**
     * @description 保存课程发布信息
     * @param courseId  课程id
     */
    private void saveCoursePublish(Long courseId){
        //整合课程发布信息
        //查询课程预发布表
        CoursePublishPre coursePublishPre = coursePublishPreService.getById(courseId);
        if(coursePublishPre == null){
            throw new bkSchoolException("课程预发布数据为空");
        }
        CoursePublish coursePublish = new CoursePublish();
        //拷贝到课程发布对象
        BeanUtils.copyProperties(coursePublishPre,coursePublish);
        coursePublish.setStatus("203002");
        CoursePublish coursePublishUpdate = coursePublishMapper.selectById(courseId);
        if(coursePublishUpdate == null){
            coursePublishMapper.insert(coursePublish);
        }else{
            coursePublishMapper.updateById(coursePublish);
        }
        //更新课程基本表的发布状态
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        courseBase.setStatus("203002");
        courseBaseMapper.updateById(courseBase);
    }

    /**
     * @description 保存消息表记录
     * @param courseId  课程id
     */
    private void saveCoursePublishMessage(Long courseId){
        MqMessage mqMessage = mqMessageService.addMessage(CoursePublishTask.MESSAGE_TYPE, String.valueOf(courseId), null, null);
        if(mqMessage==null){
            throw new bkSchoolException("业务异常，添加消息记录失败");
        }
    }

    /**
     * @description 生成静态页面
     * @param courseId  课程id
     * @return 静态页面文件
     */
    @Override
    public File generateCourseHtml(Long courseId) {
        //静态化文件
        File htmlFile  = null;
        try {
            //配置freemarker
            Configuration configuration = new Configuration(Configuration.getVersion());
            //加载模板
            //选指定模板路径,classpath下templates下
            //得到classpath路径
            String classpath = Objects.requireNonNull(this.getClass().getResource("/")).getPath();
            configuration.setDirectoryForTemplateLoading(new File(classpath + "/templates/"));
            //设置字符编码
            configuration.setDefaultEncoding("utf-8");
            //指定模板文件名称
            Template template = configuration.getTemplate("course_template.ftl");
            //准备数据
            CoursePreviewDto coursePreviewInfo = this.getCoursePreviewInfo(courseId);
            Map<String, Object> map = new HashMap<>();
            map.put("model", coursePreviewInfo);
            //静态化
            //参数1：模板，参数2：数据模型
            String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
//            System.out.println(content);
            //将静态化内容输出到文件中
            InputStream inputStream = IOUtils.toInputStream(content);
            //创建静态化文件
            htmlFile = File.createTempFile("course",".html");
            log.debug("课程静态化，生成静态文件:{}",htmlFile.getAbsolutePath());
            //输出流
            FileOutputStream outputStream = new FileOutputStream(htmlFile);
            IOUtils.copy(inputStream, outputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return htmlFile;
    }

    /**
     * @description  上传静态页面
     * @param courseId 课程Id
     * @param file  静态化文件
     */
    @Override
    public void uploadCourseHtml(Long courseId, File file) {
        MultipartFile multipartFile = MultipartSupportConfig.getMultipartFile(file);
        mediaServiceClient.uploadFile(multipartFile, "course", courseId+".html");
    }

    /**
     * @param courseId 课程Id
     * @description 保存课程索引
     */
    @Override
    public void saveCourseIndex(long courseId) {
        //取出课程发布信息
        CoursePublish coursePublish = coursePublishMapper.selectById(courseId);
        if (coursePublish == null){
            throw new bkSchoolException("系统异常，没有找到该课程信息");
        }
        //拷贝至课程索引对象
        CourseIndex courseIndex = new CourseIndex();
        BeanUtils.copyProperties(coursePublish,courseIndex);
        //远程调用搜索服务api添加课程信息到索引
        Boolean add = searchServiceClient.add(courseIndex);
        if(!add){
            throw new bkSchoolException("添加索引失败");
        }
    }


}
